<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>Taro跨平台开发实践 | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="Taro,">
  

  <meta name="description" content="一、小程序开发框架 Vue-like、React-like 代码，如何在小程序中运行?  1.1 基本原理 编译时处理（转译成小程序语法） 运行时适配（管理生命周期、数据，处理事件等）  编译原理  源代码-&amp;gt;词法/语法/语义分析-&amp;gt;抽象语法树-&amp;gt;转换-&amp;gt;目标代码   抽象语法树 AST  1.2 小程序框架多端支持情况 二、Taro原理 Taro: 多端统一开发框架，支持">
<meta name="keywords" content="Taro">
<meta property="og:type" content="article">
<meta property="og:title" content="Taro跨平台开发实践">
<meta property="og:url" content="http://blog.poetries.top/2019/06/08/taro-summary/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="一、小程序开发框架 Vue-like、React-like 代码，如何在小程序中运行?  1.1 基本原理 编译时处理（转译成小程序语法） 运行时适配（管理生命周期、数据，处理事件等）  编译原理  源代码-&amp;gt;词法/语法/语义分析-&amp;gt;抽象语法树-&amp;gt;转换-&amp;gt;目标代码   抽象语法树 AST  1.2 小程序框架多端支持情况 二、Taro原理 Taro: 多端统一开发框架，支持">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/1.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/2.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/3.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/4.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/5.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/6.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/7.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/8.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/9.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/10.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/11.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/12.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/13.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/14.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/15.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/16.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/17.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/18.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/19.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/20.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/21.png">
<meta property="og:image" content="https://poetries1.gitee.io/img-repo/20190930/22.png">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/1480597-4032f18cd94f7871.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/1480597-58be0cdf0230802f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2020-08-15T04:25:31.934Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Taro跨平台开发实践">
<meta name="twitter:description" content="一、小程序开发框架 Vue-like、React-like 代码，如何在小程序中运行?  1.1 基本原理 编译时处理（转译成小程序语法） 运行时适配（管理生命周期、数据，处理事件等）  编译原理  源代码-&amp;gt;词法/语法/语义分析-&amp;gt;抽象语法树-&amp;gt;转换-&amp;gt;目标代码   抽象语法树 AST  1.2 小程序框架多端支持情况 二、Taro原理 Taro: 多端统一开发框架，支持">
<meta name="twitter:image" content="https://poetries1.gitee.io/img-repo/20190930/1.png">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、小程序开发框架"><span class="toc-text">一、小程序开发框架</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-基本原理"><span class="toc-text">1.1 基本原理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-小程序框架多端支持情况"><span class="toc-text">1.2 小程序框架多端支持情况</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、Taro原理"><span class="toc-text">二、Taro原理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#三、Taro项目中遇到的坑"><span class="toc-text">三、Taro项目中遇到的坑</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-一些坑"><span class="toc-text">3.1 一些坑</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-注意事项"><span class="toc-text">3.2 注意事项</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#四、技巧"><span class="toc-text">四、技巧</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-样式文件条件编译"><span class="toc-text">4.1 样式文件条件编译</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-2-内置环境变量"><span class="toc-text">4.2 内置环境变量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-3-统一接口的多端文件"><span class="toc-text">4.3 统一接口的多端文件</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#五、React-Native端的实践"><span class="toc-text">五、React Native端的实践</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#5-1-Taro运行RN步骤"><span class="toc-text">5.1 Taro运行RN步骤</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-2-样式"><span class="toc-text">5.2 样式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#5-3-问题"><span class="toc-text">5.3 问题</span></a></li></ol></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-taro-summary" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">Taro跨平台开发实践</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2019.06.08</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 2k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 8分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <h2 id="一、小程序开发框架"><a href="#一、小程序开发框架" class="headerlink" title="一、小程序开发框架"></a>一、小程序开发框架</h2><p><img src="https://poetries1.gitee.io/img-repo/20190930/1.png" alt="image.png"></p>
<p><strong>Vue-like、React-like 代码，如何在小程序中运行?</strong></p>
<p><img src="https://poetries1.gitee.io/img-repo/20190930/2.png" alt="image.png"></p>
<h3 id="1-1-基本原理"><a href="#1-1-基本原理" class="headerlink" title="1.1 基本原理"></a>1.1 基本原理</h3><ul>
<li>编译时处理（转译成小程序语法）</li>
<li>运行时适配（管理生命周期、数据，处理事件等）</li>
</ul>
<p><strong>编译原理</strong></p>
<blockquote>
<p>源代码-&gt;词法/语法/语义分析-&gt;抽象语法树-&gt;转换-&gt;目标代码</p>
</blockquote>
<p><img src="https://poetries1.gitee.io/img-repo/20190930/3.png" alt="image.png"></p>
<p><strong>抽象语法树 AST</strong></p>
<p><img src="https://poetries1.gitee.io/img-repo/20190930/4.png" alt="image.png"></p>
<h3 id="1-2-小程序框架多端支持情况"><a href="#1-2-小程序框架多端支持情况" class="headerlink" title="1.2 小程序框架多端支持情况"></a>1.2 小程序框架多端支持情况</h3><p><img src="https://poetries1.gitee.io/img-repo/20190930/5.png" alt="image.png"></p>
<h2 id="二、Taro原理"><a href="#二、Taro原理" class="headerlink" title="二、Taro原理"></a>二、Taro原理</h2><blockquote>
<p>Taro: 多端统一开发框架，支持用 React 的开发方式编写一次代<br>码，生成能运行在微信小程序、H5、React Native 等的应用</p>
</blockquote>
<p><img src="https://poetries1.gitee.io/img-repo/20190930/6.png" alt="image.png"><br><img src="https://poetries1.gitee.io/img-repo/20190930/7.png" alt="image.png"><br><img src="https://poetries1.gitee.io/img-repo/20190930/8.png" alt="image.png"><br><img src="https://poetries1.gitee.io/img-repo/20190930/9.png" alt="image.png"></p>
<p><strong>多端能力：提供对应端的runtime、组件、redux、router等实现</strong></p>
<p><img src="https://poetries1.gitee.io/img-repo/20190930/10.png" alt="image.png"><br><img src="https://poetries1.gitee.io/img-repo/20190930/11.png" alt="image.png"><br><img src="https://poetries1.gitee.io/img-repo/20190930/12.png" alt="image.png"><br><img src="https://poetries1.gitee.io/img-repo/20190930/13.png" alt="image.png"></p>
<ul>
<li>提供相应端的 <code>Runtime</code> 实现，具备适配 <code>API</code> 的能力</li>
<li>提供统一的基础组件，编译时替换为相应端的组件实现</li>
</ul>
<h2 id="三、Taro项目中遇到的坑"><a href="#三、Taro项目中遇到的坑" class="headerlink" title="三、Taro项目中遇到的坑"></a>三、Taro项目中遇到的坑</h2><h3 id="3-1-一些坑"><a href="#3-1-一些坑" class="headerlink" title="3.1 一些坑"></a>3.1 一些坑</h3><p><strong>1、React-like，不完全等同 React</strong></p>
<p><img src="https://poetries1.gitee.io/img-repo/20190930/14.png" alt="image.png"></p>
<p><strong>2、端能力差异不可避免：某些功能在相应端上没有支持</strong></p>
<p><img src="https://poetries1.gitee.io/img-repo/20190930/15.png" alt="image.png"></p>
<p><strong>3、样式支持、写法上存在差异</strong></p>
<p><img src="https://poetries1.gitee.io/img-repo/20190930/16.png" alt="image.png"><br><img src="https://poetries1.gitee.io/img-repo/20190930/17.png" alt="image.png"><br><img src="https://poetries1.gitee.io/img-repo/20190930/18.png" alt="image.png"></p>
<p><strong>4、还没有真正支持多端的 UI 组件库能在 Taro 上使用</strong></p>
<p><img src="https://poetries1.gitee.io/img-repo/20190930/19.png" alt="image.png"></p>
<p><strong>5、React Native 的 view 不支持 click 事件，需要用 Touchable 组件</strong></p>
<p><img src="https://poetries1.gitee.io/img-repo/20190930/20.png" alt="image.png"></p>
<p><strong>6、React Native 不支持 text-overflow，而是提供原生支持（Text 组件传入 numberOfLines={num} 属性）</strong></p>
<blockquote>
<p><code>Taro</code> 目前没有暴露原生 <code>RN</code> T<code>ext</code> 组件的 <code>numberOfLines</code> 属性。因此目前通过 <code>Text</code> 基础组件没法实现多端统一的文本截断</p>
</blockquote>
<p><strong>H5情况较为乐观</strong></p>
<ul>
<li>主要差异1: 小程序的页面、组件样式都是独立的，H5会受同名样式影响</li>
<li>主要差异2: 小程序的组件多了一层标签</li>
</ul>
<p><img src="https://poetries1.gitee.io/img-repo/20190930/21.png" alt="image.png"></p>
<p><strong>7、多端要求较高</strong></p>
<ul>
<li>对不同端的具体差异有所了解</li>
<li>样式实现较为苛刻，需兼顾多端、有所取舍</li>
<li>端能力差异可能需要自己填坑</li>
</ul>
<p><strong>8、多端填坑方式</strong></p>
<p><img src="https://poetries1.gitee.io/img-repo/20190930/22.png" alt="image.png"></p>
<p><strong>多端实践经验</strong></p>
<ul>
<li>对多端差异做好封装</li>
<li>采用 BEM 命名方式管理样式</li>
<li>采用全局样式维护基础组件 <code>@taro/components</code> 的样式</li>
<li>基于 <code>@taro/components</code> 自行封装组件库</li>
</ul>
<h3 id="3-2-注意事项"><a href="#3-2-注意事项" class="headerlink" title="3.2 注意事项"></a>3.2 注意事项</h3><ul>
<li>函数需要<code>on+函数名</code>来规范命名</li>
<li>子组件中接收的<code>props</code>需要定义<code>defaultProps</code>。否则小程序端报错</li>
<li>在 <code>Taro</code> 中，<code>JS</code> 代码里必须书写单引号，特别是 JSX 中，如果出现双引号，可能会导致编译错误</li>
<li><code>css</code>样式单位写<code>PX</code>大写会转成<code>rem</code>单位</li>
<li>根据环境变量引入不同平台组件、编译到对应平台</li>
<li>小程序端不支持在<code>render()</code>之外定义jsx。比如在外面<code>renderForm()</code></li>
<li>页面布局：拆分组件方法–由上到下，由左到右拆分</li>
<li>Taro 目前还没有支持 <code>React.Fragment</code> 语法</li>
<li>运行时 报缺少包，需要要在 <code>.rn_temp</code> 目录里面安装</li>
<li>文字要包在 <code>Text</code> 组件里面，否则不显示</li>
<li><code>position:fixed</code> <code>React Native</code> 不支持</li>
<li><code>Animation</code> 和 <code>transform</code> <code>React Native</code> 动画不支持</li>
<li>状态更新一定是异步的。React的状态更新不一定是异步</li>
</ul>
<h2 id="四、技巧"><a href="#四、技巧" class="headerlink" title="四、技巧"></a>四、技巧</h2><h3 id="4-1-样式文件条件编译"><a href="#4-1-样式文件条件编译" class="headerlink" title="4.1 样式文件条件编译"></a>4.1 样式文件条件编译</h3><blockquote>
<p>假设目录中同时存在以下文件：</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">- index.scss</span><br><span class="line">- index.rn.scss</span><br></pre></td></tr></table></figure>
<blockquote>
<p>当在 <code>JS</code>文件中引用样式文件：<code>import &#39;./index.scss&#39;</code> 时，<code>RN</code> 平台会找到并引入 <code>index.rn.scss</code>，其他平台会引入：<code>index.scss</code>，方便大家书写跨端样式，更好地兼容 <code>RN</code></p>
</blockquote>
<h3 id="4-2-内置环境变量"><a href="#4-2-内置环境变量" class="headerlink" title="4.2 内置环境变量"></a>4.2 内置环境变量</h3><p><strong>process.env.TARO_ENV</strong></p>
<blockquote>
<p>用于判断当前编译类型，目前有 <code>weapp / swan / alipay / h5 / rn / tt</code>六个取值，可以通过这个变量来书写对应一些不同环境下的代码，在编译时会将不属于当前编译类型的代码去掉，只保留当前编译类型下的代码，例如想在微信小程序和 H5 端分别引用不同资源</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> (process.env.TARO_ENV === <span class="string">'weapp'</span>) &#123;</span><br><span class="line">  <span class="built_in">require</span>(<span class="string">'path/to/weapp/name'</span>)</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (process.env.TARO_ENV === <span class="string">'h5'</span>) &#123;</span><br><span class="line">  <span class="built_in">require</span>(<span class="string">'path/to/h5/name'</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>同时也可以在 <code>JSX</code> 中使用，决定不同端要加载的组件</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">render () &#123;</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;View&gt;</span><br><span class="line">      &#123;process.env.TARO_ENV === <span class="string">'weapp'</span> &amp;&amp; <span class="xml"><span class="tag">&lt;<span class="name">ScrollViewWeapp</span> /&gt;</span></span>&#125;</span><br><span class="line">      &#123;process.env.TARO_ENV === <span class="string">'h5'</span> &amp;&amp; <span class="xml"><span class="tag">&lt;<span class="name">ScrollViewH5</span> /&gt;</span></span>&#125;</span><br><span class="line">    &lt;<span class="regexp">/View&gt;</span></span><br><span class="line"><span class="regexp">  )</span></span><br><span class="line"><span class="regexp">&#125;</span></span><br></pre></td></tr></table></figure>
<h3 id="4-3-统一接口的多端文件"><a href="#4-3-统一接口的多端文件" class="headerlink" title="4.3 统一接口的多端文件"></a>4.3 统一接口的多端文件</h3><p><strong>多端组件</strong></p>
<ul>
<li>假如有一个 Test 组件存在微信小程序、百度小程序和 H5 三个不同版本，那么就可以像如下组织代码</li>
<li><code>test.js</code> 文件，这是 <code>Test</code> 组件默认的形式，编译到微信小程序、百度小程序和 H5 三端之外的端使用的版本</li>
<li><code>test.h5.js</code> 文件，这是 <code>Test</code> 组件的 <code>H5</code> 版本</li>
<li><code>test.weapp.js</code> 文件，这是 <code>Test</code>组件的 微信小程序 版本</li>
<li><code>test.swan.js</code> 文件，这是 <code>Test</code> 组件的 百度小程序 版本</li>
<li>四个文件，对外暴露的是统一的接口，它们接受一致的参数，只是内部有针对各自平台的代码实现</li>
<li>而我们使用 <code>Test</code> 组件的时候，引用的方式依然和之前保持一致，<code>import</code> 的是不带端类型的文件名，在编译的时候会自动识别并添加端类型后缀</li>
</ul>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">import Test from &apos;../../components/test&apos;</span><br><span class="line"></span><br><span class="line">&lt;Test argA=&#123;1&#125; argA=&#123;2&#125; /&gt;</span><br></pre></td></tr></table></figure>
<p><strong>多端脚本逻辑</strong></p>
<blockquote>
<p>例如微信小程序上使用 <code>Taro.setNavigationBarTitle</code> 来设置页面标题，H5 使用 <code>document.title</code>，那么可以封装一个 <code>setTitle</code> 方法来抹平两个平台的差异</p>
</blockquote>
<p>增加 <code>set_title.h5.js</code>，代码如下</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> <span class="title">setTitle</span> (<span class="params">title</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">document</span>.title = title</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>增加 <code>set_title.weapp.js</code>，代码如下</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> Taro <span class="keyword">from</span> <span class="string">'@tarojs/taro'</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span> <span class="title">setTitle</span> (<span class="params">title</span>) </span>&#123;</span><br><span class="line">  Taro.setNavigationBarTitle(&#123;</span><br><span class="line">    title</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>调用的时候，如下使用</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">import setTitle from &apos;../utils/set_title&apos;</span><br><span class="line"></span><br><span class="line">setTitle(&apos;页面标题&apos;)</span><br></pre></td></tr></table></figure>
<h2 id="五、React-Native端的实践"><a href="#五、React-Native端的实践" class="headerlink" title="五、React Native端的实践"></a>五、React Native端的实践</h2><blockquote>
<p><a href="https://nervjs.github.io/taro/docs/react-native.html" target="_blank" rel="noopener">https://nervjs.github.io/taro/docs/react-native.html</a></p>
</blockquote>
<h3 id="5-1-Taro运行RN步骤"><a href="#5-1-Taro运行RN步骤" class="headerlink" title="5.1 Taro运行RN步骤"></a>5.1 Taro运行RN步骤</h3><p><strong>1. 运行 yarn dev:rn</strong></p>
<p><img src="https://upload-images.jianshu.io/upload_images/1480597-4032f18cd94f7871.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png"></p>
<blockquote>
<p>打开 <a href="http://127.0.0.1:8081/index.bundle?platform=ios&amp;dev=true激活编译" target="_blank" rel="noopener">http://127.0.0.1:8081/index.bundle?platform=ios&amp;dev=true激活编译</a></p>
</blockquote>
<p><img src="https://upload-images.jianshu.io/upload_images/1480597-58be0cdf0230802f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png"></p>
<p><strong>2. 下载react-native运行壳子</strong></p>
<blockquote>
<p><a href="https://github.com/poetries/react-native-shell" target="_blank" rel="noopener">https://github.com/poetries/react-native-shell</a></p>
</blockquote>
<p><strong>3. 打开gemotion安卓模拟器</strong></p>
<blockquote>
<ul>
<li><a href="http://blog.poetries.top/2019/06/08/rn-summary/#1-1-2-%E5%AE%89%E5%8D%93%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA">参考文章</a> </li>
<li><code>adb devices</code> 查看是否有设备在运行</li>
</ul>
</blockquote>
<p><strong>4. 启动安卓</strong></p>
<blockquote>
<p>在壳子中启动命令。<code>react-native-shell</code> 放在哪里都可以，建议放到项目根目录即可</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">react-native run-android</span><br></pre></td></tr></table></figure>
<p><strong>5. 打包apk</strong></p>
<p>把<code>react-native-shell</code>中的<code>android</code>文件加拷贝到<code>.rn_temp</code>文件中，<code>cd android</code> 执行打包命令即可</p>
<blockquote>
<p><a href="http://blog.poetries.top/2019/06/08/rn-summary/#%E5%85%AB%E3%80%81%E6%89%93%E5%8C%85">参考文章</a></p>
</blockquote>
<h3 id="5-2-样式"><a href="#5-2-样式" class="headerlink" title="5.2 样式"></a>5.2 样式</h3><blockquote>
<p>Note：如果要支持 <code>React Native</code> 端，必须采用 Flex 布局，并且样式选择器仅支持类选择器，且不 支持 组合器</p>
</blockquote>
<p>以下选择器的写法都是不支持的，在样式转换时会自动忽略</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">.button.button_theme_islands&#123;</span><br><span class="line">  font-style: bold;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">img + p &#123;</span><br><span class="line">  font-style: bold;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">p ~ span &#123;</span><br><span class="line">  color: red;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">div &gt; span &#123;</span><br><span class="line">  background-color: DodgerBlue;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">div span &#123; background-color: DodgerBlue; &#125;</span><br></pre></td></tr></table></figure>
<p>样式上 <code>H5</code> 最为灵活，小程序次之，<code>RN</code> 最弱，统一多端样式即是对齐短板，也就是要以 <code>RN</code> 的约束来管理样式，同时兼顾小程序的限制，核心可以用三点来概括</p>
<ul>
<li>使用 <code>Flex</code> 布局</li>
<li>基于 <code>BEM</code> 写样式</li>
<li>采用 <code>style</code> 属性覆盖组件样式</li>
</ul>
<blockquote>
<p><code>RN</code> 中 <code>View</code> 标签默认主轴方向是 <code>column</code>，如果不将其他端改成与 RN 一致，就需要在所有用到 <code>display: flex</code> 的地方都显式声明主轴方向</p>
</blockquote>
<h3 id="5-3-问题"><a href="#5-3-问题" class="headerlink" title="5.3 问题"></a>5.3 问题</h3><p><strong>尽量避免在 componentDidMount 中调用 this.setState</strong></p>
<blockquote>
<p>因为在 <code>componentDidMount</code> 中调用 <code>this.setState</code> 会导致触发更新</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> Taro, &#123; Component &#125; <span class="keyword">from</span> <span class="string">'@tarojs/taro'</span></span><br><span class="line"><span class="keyword">import</span> &#123; View, Input &#125; <span class="keyword">from</span> <span class="string">'@tarojs/components'</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyComponent</span> <span class="keyword">extends</span> <span class="title">Component</span> </span>&#123;</span><br><span class="line">  state = &#123;</span><br><span class="line">    myTime: <span class="number">12</span></span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  componentDidMount () &#123;</span><br><span class="line">    <span class="keyword">this</span>.setState(&#123;     <span class="comment">// ✗ 尽量避免，可以在 componentWillMount 中处理</span></span><br><span class="line">      name: <span class="number">1</span></span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  render () &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; isEnable &#125; = <span class="keyword">this</span>.props</span><br><span class="line">    <span class="keyword">const</span> &#123; myTime &#125; = <span class="keyword">this</span>.state</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">      &lt;View className=<span class="string">'test'</span>&gt;</span><br><span class="line">        &#123;isEnable &amp;&amp; <span class="xml"><span class="tag">&lt;<span class="name">Text</span> <span class="attr">className</span>=<span class="string">'test_text'</span>&gt;</span>&#123;myTime&#125;<span class="tag">&lt;/<span class="name">Text</span>&gt;</span></span>&#125;</span><br><span class="line">      &lt;<span class="regexp">/View&gt;</span></span><br><span class="line"><span class="regexp">    )</span></span><br><span class="line"><span class="regexp">  &#125;</span></span><br><span class="line"><span class="regexp">&#125;</span></span><br></pre></td></tr></table></figure>
<p><strong>不要定义没有用到的 state</strong></p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> Taro, &#123; Component &#125; <span class="keyword">from</span> <span class="string">'@tarojs/taro'</span></span><br><span class="line"><span class="keyword">import</span> &#123; View, Input &#125; <span class="keyword">from</span> <span class="string">'@tarojs/components'</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyComponent</span> <span class="keyword">extends</span> <span class="title">Component</span> </span>&#123;</span><br><span class="line">  state = &#123;</span><br><span class="line">    myTime: <span class="number">12</span>,</span><br><span class="line">    noUsed: <span class="literal">true</span>   <span class="comment">// ✗ 没有用到</span></span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  render () &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; myTime &#125; = <span class="keyword">this</span>.state</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">      &lt;View className=<span class="string">'test'</span>&gt;</span><br><span class="line">        &lt;Text className=<span class="string">'test_text'</span>&gt;&#123;myTime&#125;&lt;<span class="regexp">/Text&gt;</span></span><br><span class="line"><span class="regexp">      &lt;/</span>View&gt;</span><br><span class="line">    )</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2019/06/08/rn-summary/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2019/06/08/ionic3-to-ionic4/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
